package com.goodrain.springbootdemo.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.goodrain.springbootdemo.vo.RestResponse;
import com.goodrain.springbootdemo.vo.User;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class RestfulDemoService {
    public User fetchUser() throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        //  httpclient 文档: https://hc.apache.org/httpcomponents-client-ga/quickstart.html
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://127.0.0.1:5000/get-user");
        CloseableHttpResponse resp = httpclient.execute(httpGet);
        RestResponse<User> r = null;
        User user = null;
        try {
            System.out.println(resp.getStatusLine());
            // TODO: 处理http状态码
            HttpEntity entity = resp.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            r = mapper.readValue(entity.getContent(), new TypeReference<RestResponse<User>>() {
            });

            if (r.getSuccess() == 0) {
                user = r.getData();
            } else {
                // TODO: RestResponse 中的 code 进行相应处理
            }

            EntityUtils.consume(entity);
        } finally {
            resp.close();
        }
        return user;
    }
}
